<template>
  <div class="commission-withdraw">
    <h1 class="page-title">佣金提现</h1>

    <!-- 提现概览 -->
    <div class="overview-card">
      <div class="overview-item available">
        <div class="item-title">可提现佣金</div>
        <div class="item-value">¥{{ userDataInfo.withdraw_funds || 0 }}</div>
      </div>
      <div class="overview-item pending">
        <div class="item-title">待结算佣金</div>
        <div class="item-value">¥{{ userDataInfo.wait_money || 0 }}</div>
      </div>
      <div class="overview-item settled">
        <div class="item-title">已结算佣金</div>
        <div class="item-value">¥{{ userDataInfo.withdrawal_money || 0 }}</div>
      </div>
      <div class="overview-item fee">
        <div class="item-title">本月佣金总额</div>
        <div class="item-value">{{ userDataInfo.month_money_total || 0 }}</div>
      </div>
      <div class="overview-item fee">
        <div class="item-title">累计佣金总额</div>
        <div class="item-value">
          {{ userDataInfo.commission_money_total || 0 }}
        </div>
      </div>
    </div>

    <!-- 地址修改表单 -->
    <div class="withdraw-form-card" v-if="!addressUsdt || !addressPaypal">
      <h2 class="card-title">我的地址</h2>
      <form @submit.prevent="submitAddress" class="withdraw-form">

        <div class="form-group">
          <label>
            <el-form-item label="USDT提现地址" prop="address_usdt"  v-if="!addressUsdt">
              <el-input v-model="addressUsdtShow" type="textarea" />
            </el-form-item>
            <el-form-item label="paypal提现地址" prop="address_paypal" v-if="!addressPaypal">
              <el-input v-model="addressPaypalShow"  type="textarea"/>
            </el-form-item>
          </label>
        </div>
        <div class="form-group">
          <button type="submit" class="submit-btnc">
            <span v-if="addressSubmitting">处理中...</span>
            <span v-else>确认添加地址</span>
          </button>
        </div>
      </form>
    </div>

    <!-- 提现表单 -->
    <div class="withdraw-form-card">
      <h2 class="card-title">申请提现</h2>
      <form @submit.prevent="submitWithdrawal" class="withdraw-form">
        <div class="form-group">
          <label for="money">提现金额</label>
          <div class="money-input-wrapper">
            <input
              type="number"
              id="money"
              v-model="withdrawalForm.money"
              min="1"
              :max="overviewData.availableAmount"
              step="0.01"
              placeholder="最小提现金额为1元"
              required
            />
            <span class="currency-symbol">¥</span>
          </div>

          <div class="money-info">
            <span>可提金额: ¥{{ userDataInfo.withdraw_funds }}</span>
          </div>

          <div v-if="formErrors.money" class="error-message">
            {{ formErrors.money }}
          </div>
        </div>

        <div class="form-group">
          <label>
            <span
              class="payment-option"
              :class="{ selected: selectedPayment === 'paypal' }"
              @click="selectPayment('paypal',1)"
            >
              pay地址手续费：{{ userDataInfo.address_paypal_lv }}% <br />
              pay地址：{{ userDataInfo.address_paypal }}<br />
              获得金额：{{ withdrawalForm.money - (userDataInfo.address_paypal_lv * withdrawalForm.money/100 ) }}
            </span>

            <span
              class="payment-option"
              :class="{ selected: selectedPayment === 'usdt' }"
              @click="selectPayment('usdt',0)"
            >
               usdt手续费：{{ userDataInfo.address_usdt_lv }}%
              <br />
              usdt地址：{{ userDataInfo.address_usdt }}
                 <br />
              获得金额：{{ withdrawalForm.money - (userDataInfo.address_usdt_lv * withdrawalForm.money/100 ) }}
            </span>
          </label>
        </div>
        <div class="form-group">
          <button type="submit" class="submit-btn">
            <span v-if="submitting">处理中...</span>
            <span v-else>确认提现</span>
          </button>
        </div>
      </form>
    </div>

    <!-- 提现记录 -->
    <WithdrawalRecordsTable ref="withdrawalRecordsTableRef" />

    <!-- 提现详情弹窗 -->
    <div v-if="detailModalVisible" class="detail-modal">
      <div class="modal-backdrop" @click="detailModalVisible = false"></div>
      <div class="modal-content">
        <div class="modal-header">
          <h3>提现详情</h3>
          <button class="close-btn" @click="detailModalVisible = false">
            ×
          </button>
        </div>
        <div class="modal-body">
          <div class="detail-section">
            <div class="detail-item">
              <span class="label">提现单号</span>
              <span class="value">{{ currentRecord?.id }}</span>
            </div>
            <div class="detail-item">
              <span class="label">到账金额</span>
              <span class="value">¥{{ currentRecord?.money.toFixed(2) }}</span>
            </div>
          </div>

          <div class="timeline-section">
            <h4>处理进度</h4>
            <div class="timeline">
              <div
                v-for="(item, index) in currentRecord?.timeline"
                :key="index"
                class="timeline-item"
                :class="{ completed: true }"
              >
                <div class="timeline-point" :class="item.status"></div>
                <div class="timeline-content">
                  <div class="timeline-date">
                    {{ formatDateTime(item.time) }}
                  </div>
                  <div class="timeline-description">{{ item.description }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 提现成功弹窗 -->
    <div v-if="successModalVisible" class="success-modal">
      <div class="modal-backdrop" @click="successModalVisible = false"></div>
      <div class="modal-content">
        <div class="modal-header">
          <h3>提现申请已提交</h3>
          <button class="close-btn" @click="successModalVisible = false">
            ×
          </button>
        </div>
        <div class="modal-body">
          <div class="success-icon">
            <i class="fas fa-check-circle"></i>
          </div>
          <p class="success-message">您的提现申请已成功提交，我们将尽快处理</p>
          <div class="success-detail">
            <div class="detail-item">
              <span class="label">提现金额</span>
              <span class="value">¥{{ lastSubmittedAmount.toFixed(2) }}</span>
            </div>
          </div>
          <button
            class="close-success-btn"
            @click="successModalVisible = false"
          >
            关闭
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, onMounted } from 'vue';
  import { generateWithdrawalRecordsData } from '@/utils/agentMock';
  import {
    getRegionUserDataInfoApi, SerRegionUserDataEdit, SerUserDataEdit,
    SetRegionPayWithdrawal,
  } from '@/api/index';
  import { ElMessage } from 'element-plus';
  import WithdrawalRecordsTable from './WithdrawalRecordsTable.vue';

  // 提现概览数据
  const overviewData = reactive({

  });

  const selectedPayment = ref(''); // 'paypal' or 'usdt'

  const selectPayment = (type: string,uu:number) => {
      withdrawalForm.address = uu
    selectedPayment.value = type;
  };
  // 提现表单
  const withdrawalForm = reactive({
    money: '',
    address: '',
    role: 2,
  });

  // 表单错误信息
  const formErrors = reactive({
    money: '',
    address: '',
  });

  // 已保存的USDT地址
  const savedAddresses = ref([
  ]);

  // 提现记录
  const withdrawalRecords = ref([]);
  const loading = ref(false);
  const filters = reactive({
    startDate: '',
    endDate: '',
    status: '',
  });

  // 模态框状态
  const detailModalVisible = ref(false);
  const successModalVisible = ref(false);
  const currentRecord = ref(null);
  const submitting = ref(false);
  const addressSubmitting = ref(false);

  const lastSubmittedAmount = ref(0);
  const lastSubmittedAddress = ref('');

  const addressUsdt = ref(null);
  const addressPaypal = ref(null);
  const addressPaypalShow = ref(null);
  const addressUsdtShow = ref(null);
  const fetchWithdrawalRecords = () => {
    loading.value = true;

    try {
      const records = generateWithdrawalRecordsData({
        startDate: filters.startDate || undefined,
        endDate: filters.endDate || undefined,
        status: filters.status || undefined,
      });

      withdrawalRecords.value = records;
    } catch (error) {
      console.error('获取提现记录失败:', error);
    } finally {
      loading.value = false;
    }
  };

  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  };

  const formatDateTime = (dateString) => {
    const date = new Date(dateString);
    return `${formatDate(dateString)} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  };

  // 生命周期钩子
  onMounted(() => {
    // fetchWithdrawalRecords();
    getUserDataInfoRequest();
  });

  // ------------------------------

  const withdrawalRecordsTableRef = ref();

  const submitAddress = async () => {
    addressSubmitting.value = true;
    try {
      const res = await SerRegionUserDataEdit({address_usdt:addressUsdtShow.value,address_paypal:addressPaypalShow.value});
      if (res.code == 200){
        alert(res.msg);
        location.reload();
      }
    } catch (error) {
      alert(error.msg);
    } finally {
      submitting.value = false;
    }
  }
  const submitWithdrawal = async () => {
    // 表单验证
    // 显示提交中状态
    submitting.value = true;

    if (withdrawalForm.money == ""){
      console.log(withdrawalForm.address)
      console.log(withdrawalForm.money)
      alert('请填写提现数据');
      submitting.value = false;
      return;
    }

    try {
      const res = await SetRegionPayWithdrawal(withdrawalForm);
      // 保存提交信息，用于成功弹窗显示
      lastSubmittedAmount.value = parseFloat(withdrawalForm.money);
      lastSubmittedAddress.value = withdrawalForm.address;

      // 重置表单
      withdrawalForm.money = '';
      withdrawalForm.address = '';

      // 模拟提现后余额减少
      //overviewData.availableAmount -= lastSubmittedAmount.value;

      // 显示成功弹窗
      successModalVisible.value = true;

      getUserDataInfoRequest();

      withdrawalRecordsTableRef.value.searchTable();

      // 刷新提现记录
      fetchWithdrawalRecords();
    } catch (error) {
      alert(error.msg);
    } finally {
      submitting.value = false;
    }
  };
  const userDataInfo = ref({});

  const getUserDataInfoRequest = async () => {
    try {
      const res = await getRegionUserDataInfoApi({});

       userDataInfo.value = res.data;
      addressUsdt.value = res.data.address_usdt;
      addressPaypal.value = res.data.address_paypal;
    } catch (error) {
      console.log(error);
      ElMessage({
        type: 'error',
        message: error.msg,
      });
    }
  };
</script>

<style lang="scss" scoped>
  .commission-withdraw {
    padding: 24px;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      margin-bottom: 24px;
      color: #333;
    }

    // 提现概览卡片
    .overview-card {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 20px;
      margin-bottom: 24px;

      @media (max-width: 1200px) {
        grid-template-columns: repeat(2, 1fr);
      }

      @media (max-width: 640px) {
        grid-template-columns: 1fr;
      }

      .overview-item {
        background-color: #fff;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
        border-top: 4px solid #ccc;

        &.available {
          border-top-color: #4caf50;
        }

        &.pending {
          border-top-color: #ff9800;
        }

        &.settled {
          border-top-color: #2196f3;
        }

        &.fee {
          border-top-color: #9c27b0;
        }

        .item-title {
          font-size: 14px;
          color: #666;
          margin-bottom: 8px;
        }

        .item-value {
          font-size: 24px;
          font-weight: 600;
          color: #333;
        }
      }
    }

    // 提现表单卡片
    .withdraw-form-card {
      background-color: #fff;
      border-radius: 8px;
      padding: 24px;
      margin-bottom: 24px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

      .card-title {
        font-size: 18px;
        font-weight: 600;
        margin-top: 0;
        margin-bottom: 24px;
        color: #333;
      }

      .withdraw-form {
        .form-group {
          margin-bottom: 20px;

          label {
            display: block;
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
          }

          .money-input-wrapper,
          .address-input-wrapper {
            position: relative;

            input {
              width: 100%;
              padding: 12px 16px;
              border: 1px solid #ddd;
              border-radius: 4px;
              font-size: 16px;
              transition: border-color 0.3s;

              &:focus {
                outline: none;
                border-color: #4a6cf7;
              }
            }

            .currency-symbol {
              position: absolute;
              left: 16px;
              top: 50%;
              transform: translateY(-50%);
              color: #666;
              font-size: 16px;
            }

            input[type='number'] {
              padding-left: 32px;
            }

            .use-saved-btn {
              position: absolute;
              right: 8px;
              top: 50%;
              transform: translateY(-50%);
              background: none;
              border: none;
              color: #4a6cf7;
              font-size: 14px;
              cursor: pointer;
              padding: 4px 8px;

              &:hover {
                text-decoration: underline;
              }
            }
          }

          .money-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 8px;
            font-size: 14px;
            color: #666;

            .use-max-btn {
              background: none;
              border: none;
              color: #4a6cf7;
              font-size: 14px;
              cursor: pointer;
              padding: 4px 0;

              &:hover {
                text-decoration: underline;
              }
            }
          }

          .error-message {
            color: #f44336;
            font-size: 14px;
            margin-top: 8px;
          }

          .summary-table {
            background-color: #f9f9f9;
            border-radius: 4px;
            overflow: hidden;

            .summary-row {
              display: flex;
              justify-content: space-between;
              padding: 12px 16px;
              border-bottom: 1px solid #eee;

              &:last-child {
                border-bottom: none;
              }

              &.total {
                font-weight: 600;
                background-color: #f5f5f5;
              }
            }
          }

          .submit-btn {
            width: 100%;
            padding: 12px 24px;
            background-color: #4a6cf7;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.3s;

            &:hover {
              background-color: #3a5bd7;
            }

            &:disabled {
              background-color: #c5c5c5;
              cursor: not-allowed;
            }
          }
          .submit-btnc {
            width: 100%;
            padding: 12px 24px;
            background-color: #cc4af7;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.3s;

            &:hover {
              background-color: #3a5bd7;
            }

            &:disabled {
              background-color: #c5c5c5;
              cursor: not-allowed;
            }
          }
        }
      }
    }

    // 提现记录卡片
    .withdrawal-records-card {
      background-color: #fff;
      border-radius: 8px;
      padding: 24px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;

        @media (max-width: 768px) {
          flex-direction: column;
          align-items: flex-start;
          gap: 16px;
        }

        .card-title {
          font-size: 18px;
          font-weight: 600;
          margin: 0;
          color: #333;
        }

        .filter-controls {
          display: flex;
          gap: 16px;

          @media (max-width: 640px) {
            flex-direction: column;
            width: 100%;
          }

          .date-filter {
            display: flex;
            align-items: center;

            .date-input {
              padding: 8px 12px;
              border: 1px solid #ddd;
              border-radius: 4px;
              font-size: 14px;
              width: 140px;

              &:focus {
                outline: none;
                border-color: #4a6cf7;
              }
            }

            .date-separator {
              margin: 0 8px;
              color: #666;
            }
          }

          .status-filter {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            min-width: 120px;

            &:focus {
              outline: none;
              border-color: #4a6cf7;
            }
          }
        }
      }

      // 加载和空状态
      .loading-state,
      .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 48px 0;
        color: #999;

        .spinner {
          width: 40px;
          height: 40px;
          border: 4px solid rgba(74, 108, 247, 0.1);
          border-left-color: #4a6cf7;
          border-radius: 50%;
          animation: spin 1s linear infinite;
          margin-bottom: 16px;
        }

        @keyframes spin {
          to {
            transform: rotate(360deg);
          }
        }

        i {
          font-size: 40px;
          color: #ddd;
          margin-bottom: 16px;
        }

        p {
          margin: 0;
          font-size: 16px;
        }
      }

      // 记录表格
      .records-table {
        width: 100%;
        border-collapse: collapse;

        th,
        td {
          text-align: left;
          padding: 12px 16px;
          border-bottom: 1px solid #eee;
        }

        th {
          font-weight: 600;
          color: #666;
          background-color: #f9f9f9;
          white-space: nowrap;
        }

        td {
          color: #333;
        }

        .id-cell {
          font-family: 'Courier New', monospace;
          white-space: nowrap;
        }

        .money-cell,
        .fee-cell {
          text-align: right;
        }

        .status-tag {
          display: inline-block;
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;

          &.status-pending {
            background-color: rgba(255, 152, 0, 0.1);
            color: #ff9800;
          }

          &.status-processing {
            background-color: rgba(33, 150, 243, 0.1);
            color: #2196f3;
          }

          &.status-completed {
            background-color: rgba(76, 175, 80, 0.1);
            color: #4caf50;
          }

          &.status-rejected {
            background-color: rgba(244, 67, 54, 0.1);
            color: #f44336;
          }
        }

        .action-btn {
          background: none;
          border: none;
          color: #4a6cf7;
          cursor: pointer;
          font-size: 14px;

          &:hover {
            text-decoration: underline;
          }
        }

        // 响应式表格
        @media (max-width: 992px) {
          display: block;
          overflow-x: auto;
        }
      }
    }

    // 模态框样式
    .detail-modal,
    .success-modal {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 100;
      display: flex;
      align-items: center;
      justify-content: center;

      .modal-backdrop {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
      }

      .modal-content {
        position: relative;
        background-color: #fff;
        border-radius: 8px;
        width: 90%;
        max-width: 600px;
        max-height: 90vh;
        overflow-y: auto;
        box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
        animation: modalFadeIn 0.3s;

        @keyframes modalFadeIn {
          from {
            opacity: 0;
            transform: translateY(-20px);
          }

          to {
            opacity: 1;
            transform: translateY(0);
          }
        }

        .modal-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16px 24px;
          border-bottom: 1px solid #eee;

          h3 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
            color: #333;
          }

          .close-btn {
            background: none;
            border: none;
            font-size: 24px;
            color: #999;
            cursor: pointer;
            padding: 0;
            line-height: 24px;

            &:hover {
              color: #666;
            }
          }
        }

        .modal-body {
          padding: 24px;
        }
      }
    }

    // 详情模态框内容
    .detail-section {
      margin-bottom: 24px;

      .detail-item {
        display: flex;
        margin-bottom: 12px;

        .label {
          min-width: 120px;
          color: #666;
        }

        .value {
          flex: 1;
          color: #333;
          word-break: break-all;

          &.address {
            font-family: 'Courier New', monospace;
            background-color: #f5f5f5;
            padding: 4px 8px;
            border-radius: 4px;
          }

          &.reject-reason {
            color: #f44336;
          }
        }
      }
    }

    .timeline-section {
      h4 {
        font-size: 16px;
        font-weight: 600;
        margin-top: 0;
        margin-bottom: 16px;
        color: #333;
      }

      .timeline {
        position: relative;
        padding-left: 24px;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          bottom: 0;
          left: 8px;
          width: 2px;
          background-color: #eee;
        }

        .timeline-item {
          position: relative;
          padding-bottom: 24px;

          &:last-child {
            padding-bottom: 0;
          }

          .timeline-point {
            position: absolute;
            top: 0;
            left: -24px;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            background-color: #eee;
            border: 2px solid #fff;

            &.pending {
              background-color: #ff9800;
            }

            &.processing {
              background-color: #2196f3;
            }

            &.completed {
              background-color: #4caf50;
            }

            &.rejected {
              background-color: #f44336;
            }
          }

          .timeline-content {
            padding-left: 16px;

            .timeline-date {
              font-size: 14px;
              color: #999;
              margin-bottom: 4px;
            }

            .timeline-description {
              font-size: 14px;
              color: #333;
            }
          }
        }
      }
    }

    // 成功模态框内容
    .success-modal {
      .modal-body {
        text-align: center;

        .success-icon {
          font-size: 48px;
          color: #4caf50;
          margin-bottom: 16px;
        }

        .success-message {
          font-size: 16px;
          color: #333;
          margin-bottom: 24px;
        }

        .success-detail {
          text-align: left;
          background-color: #f9f9f9;
          border-radius: 8px;
          padding: 16px;
          margin-bottom: 24px;

          .detail-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;

            &:last-child {
              margin-bottom: 0;
            }

            .label {
              color: #666;
            }

            .value {
              font-weight: 500;
              color: #333;

              &.address {
                font-family: 'Courier New', monospace;
                font-size: 14px;
                word-break: break-all;
              }
            }
          }
        }

        .close-success-btn {
          padding: 10px 24px;
          background-color: #4a6cf7;
          color: white;
          border: none;
          border-radius: 4px;
          font-size: 16px;
          cursor: pointer;
          transition: background-color 0.3s;

          &:hover {
            background-color: #3a5bd7;
          }
        }
      }
    }
  }
  .payment-option {
    display: inline-block;
    padding: 12px;
    margin: 5px;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      border-color: #4a6cf7;
      background-color: rgba(74, 108, 247, 0.05);
    }

    &.selected {
      border-color: #4a6cf7;
      background-color: rgba(74, 108, 247, 0.1);
      color: #4a6cf7;
      font-weight: 500;
    }
  }
</style>
